<?php
App::uses('AppModel', 'Model');
/**
 * Product Model
 *
 * @property Category $Category
 */
class Product extends AppModel {

	public $displayField = 'name';
	public $order = "Product.name";
	
	public $belongsTo = array(
		'Category' => array(
			'className' => 'Category',
			'foreignKey' => 'category_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		)
	);
	
	public $hasMany = array(
		'ProductImage' => array(
			'dependent' => true
		)
	);
	
	public $hasAndBelongsToMany = array(
	   'Receipe' => array(
	       'joinTable'  => 'receipe_materials'
       )
	);
	
	public function beforeDelete($cascade = true) {
		parent::beforeDelete($cascade);
		
		if($this->id) {
			$dirname = "img" . DS . "products" . DS . $this->id;
			if($dir = opendir($dirname)) {
				while($f = readdir($dir)) {
					if(!preg_match('/^\.+$/', $f)){
						@unlink($dirname . DS . $f);
					}
				}
				@rmdir($dirname);
			}
		}
		
		return true;
	}
}
